package net.NingXiaRuiTai.ShortChain.component;

import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component// 注册为组件，springboot会自动扫描该注解
@Slf4j// 日志注解
public class SmsComponent {
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private RestTemplate restTemplate;
    private static final String urlTemplate =
       // "http(s)://api.guoyangyun.com/api/sms/smsoto.htm?appkey=123456&appsecret=448484484&mobile=15000000000,17300000000&smsSignId=3ff743552d&templateId=7563abd9c95";
   "http://gyytz.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";
    //"https://api.guoyangyun.com/api/sms/smsoto.htm?mobile=%s&templateId=%s&smsSignId=%s&param=%s&appkey=%s&appsecret=%s";
    @Async("threadPoolExecutor")// 异步发送短信
    /*发送短信验证码*/
    public void sendSms(String mobile, String templateId, String smsSignId, String param) {
        //构建url用于发送短信
        String url = String.format(urlTemplate, mobile, templateId, smsSignId, param);
        //构建请求头
        HttpHeaders headers = new HttpHeaders();
        //添加请求头
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        //构建请求内容
        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("url={},发送短信验证码的响应结果：{}", url, response.getBody());
        if (response.getStatusCode() ==
                HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}",response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}",response.getBody());
        }
    }


}


